<script setup lang="ts">
  import { computed, PropType, ref } from 'vue'
  import useRepairSendGoodListService from '@/services/module/return-factory/useRepairSendGoodListService'
  import { ElMessageBox, TableInstance } from 'element-plus'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import ActualSendPostingModal from './components/actual-send-posting-modal.vue'
  import { SendGoodListItem } from './types'
  import { repairReversePosting } from '@/api/return-factory'
  import _ from 'lodash'

  const { sendGoodList, getSendGoodListLoading, getSendGoodList } = useRepairSendGoodListService()

  defineOptions({
    name: 'RepairSendGoodList',
  })

  const props = defineProps({
    repairDetail: {
      type: Object as PropType<ReturnFactoryDetail>,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  const actualSendPostingModalVisible = ref(false)
  const selectionGoodList = ref<Array<SendGoodListItem>>([])
  const goodList = computed(() => {
    const result: Array<SendGoodListItem> = []
    sendGoodList.value.forEach((item) => {
      try {
        result.push(JSON.parse(item.json))
      } catch (error) {
        // error
      }
    })

    return result
  })
  const tableInstance = ref<TableInstance | null>(null)

  const getStatusTxt = (
    status: ReturnFactoryDetailGood['status'],
  ): { txt: string; status: 'primary' | 'success' | 'info' | 'warning' } => {
    if (status === 0) {
      return {
        txt: '待审核',
        status: 'warning',
      }
    }

    if (status === 1) {
      return {
        txt: '待返厂',
        status: 'warning',
      }
    }

    if (status === 2) {
      return {
        txt: '待签收',
        status: 'warning',
      }
    }

    if (status === 3) {
      return {
        txt: '待检测',
        status: 'warning',
      }
    }

    if (status === 4) {
      return {
        txt: '处理中',
        status: 'primary',
      }
    }

    if (status === 5) {
      return {
        txt: '待寄回公司',
        status: 'warning',
      }
    }

    if (status === 6) {
      return {
        txt: '待客户签收',
        status: 'warning',
      }
    }

    if (status === 7) {
      return {
        txt: '已完成',
        status: 'success',
      }
    }

    if (status === 8) {
      return {
        txt: '已取消',
        status: 'info',
      }
    }

    if (status === 9) {
      return {
        txt: '实收未过账',
        status: 'warning',
      }
    }

    if (status === 10) {
      return {
        txt: '待发货',
        status: 'warning',
      }
    }

    if (status === 11) {
      return {
        txt: '实发未过账',
        status: 'warning',
      }
    }

    return {
      txt: '已取消',
      status: 'info',
    }
  }

  const onActualSendPostingClick = () => {
    selectionGoodList.value.length = 0
    _.cloneDeep(goodList.value)
      .filter((item) => item.status === 11)
      .forEach((item) => {
        sendGoodList.value.forEach((sendGood) => {
          try {
            const sendGoodJson = JSON.parse(sendGood.json)
            if (item.goodsSnCode === sendGoodJson.goodsSnCode) {
              item.repairGoodsId = sendGood.repairGoodsId
              selectionGoodList.value.push(item)
            }
          } catch (error) {
            // error
          }
        })
      })

    if (selectionGoodList.value.length <= 0) {
      HMessageBox.error('请选择商品')
      return
    }

    if (selectionGoodList.value.some((good) => good.status !== 11)) {
      HMessageBox.error('只能选择状态为实发未过账的商品')
      return
    }
    actualSendPostingModalVisible.value = true
  }

  const handleReversePostingClick = () => {
    selectionGoodList.value = _.cloneDeep(goodList.value).filter((item) =>
      [6, 10].includes(item.status),
    )
    const _goodList: Array<SendGoodListItem> = []
    selectionGoodList.value.forEach((item) => {
      if (
        !_goodList.map((item) => item.postingIdOnPostAtSend).includes(item.postingIdOnPostAtSend)
      ) {
        _goodList.push(item)
      }
    })
    ElMessageBox({
      title: '提示',
      message: '确定要反过账吗?',
      type: 'warning',
      autofocus: false,
      showCancelButton: true,
      async beforeClose(action, instance, done) {
        if (action === 'confirm') {
          try {
            instance.confirmButtonLoading = true
            instance.cancelButtonLoading = true
            let errMsg = ''
            for (let i = 0; i < _goodList.length; i++) {
              const _good = _goodList[i]
              const res = await repairReversePosting(
                props.repairDetail.id,
                _good.postingIdOnPostAtSend,
                6,
              )
              if (res.data.code !== 20000) {
                errMsg = res.data.message
                break
              }
            }
            instance.confirmButtonLoading = false
            instance.cancelButtonLoading = false
            if (!errMsg) {
              HMessage.success('操作成功')
              emits('update')
              done()
              return
            }
            HMessageBox.error(errMsg)
            return
          } catch (error) {
            instance.confirmButtonLoading = false
            instance.cancelButtonLoading = false
          }
          return
        }

        done()
      },
    })
  }

  defineExpose({
    getList: () => {
      getSendGoodList(props.repairDetail.id)
    },
  })
</script>

<template>
  <div v-loading="getSendGoodListLoading" class="repair-send-good-list-component">
    <div class="title">
      <div class="text">发货清单</div>
      <h-plain-button
        v-if="goodList.some((item) => item.status === 11)"
        :height="22"
        :padding-lr="6"
        @click="onActualSendPostingClick"
      >
        实发过账
      </h-plain-button>
      <h-plain-button
        v-if="goodList.some((item) => [6, 10].includes(item.status))"
        :height="22"
        :padding-lr="6"
        @click="handleReversePostingClick"
      >
        反过账
      </h-plain-button>
    </div>
    <div class="table">
      <el-table
        ref="tableInstance"
        :data="goodList"
        :border="true"
        :stripe="true"
        :max-height="300"
      >
        <!-- 序号 -->
        <el-table-column width="50" fixed="left" label="序号" type="index" :align="'center'" />

        <!-- 条码 -->
        <el-table-column width="120" label="条码" prop="goodsSnCode" show-overflow-tooltip />

        <!-- 交货单号 -->
        <el-table-column
          label="交货单号"
          show-overflow-tooltip
          width="100"
          prop="postingIdOnPostAtSend"
        />

        <!-- 产品编号 -->
        <el-table-column label="产品编号" prop="materialCode" width="100" show-overflow-tooltip />

        <!-- 产品名称 -->
        <el-table-column label="产品名称" prop="goodsName" min-width="160" show-overflow-tooltip />

        <!-- 发货物流名称 -->
        <el-table-column
          label="发货物流名称"
          prop="logisticsCompany"
          width="100"
          show-overflow-tooltip
        />

        <!-- 发货物流单号 -->
        <el-table-column
          label="发货物流单号"
          prop="logisticsNo"
          width="100"
          show-overflow-tooltip
        />

        <!-- 申请数量 -->
        <el-table-column label="申请数量" prop="sendoutQty" width="80" />

        <!-- 实发数量 -->
        <el-table-column label="实发数量" prop="sendoutActualQty" width="80" />

        <!-- 状态 -->
        <el-table-column label="状态" fixed="right" :align="'center'" width="120">
          <template #default="{ row }">
            <div class="flex_justify_center">
              <h-status :type="getStatusTxt(row.status).status">{{
                getStatusTxt(row.status).txt
              }}</h-status>
            </div>
          </template>
        </el-table-column>

        <!-- 图号 -->
        <el-table-column label="图号" prop="productDrawNo" width="80" />

        <!-- 发货日期 -->
        <el-table-column label="发货日期" prop="afterSaleSubmitDate" width="128" />

        <!-- 过账日期 -->
        <el-table-column label="过账日期" prop="postingDate" width="128" />
      </el-table>
    </div>

    <actual-send-posting-modal
      v-model="actualSendPostingModalVisible"
      :repair-id="props.repairDetail.id"
      :send-good-list="selectionGoodList"
      @update="emits('update')"
    />
  </div>
</template>

<style scoped lang="scss">
  .repair-send-good-list-component {
    display: flex;
    flex-direction: column;
    row-gap: 8px;

    .title {
      display: flex;
      align-items: center;
      column-gap: 4px;

      .text {
        padding-left: 6px;
        font-size: 12px;
        height: fit-content;
        border-left: 3px solid $primaryColor;
        font-weight: bold;
      }
    }
  }
</style>
